/**
 * 与留言相关的一系列函数，负责与数据库交互
 */
const { execSql } = require('../db/mysql')

// 获取留言列表
const getMessages = async () => {
  let sql = 'select * from messages order by created_at desc'
  try {
    const result = await execSql(sql)
    return result
  } catch (error) {
    console.log(error)
  }
}

// 获取留言对应的评论列表
const getComments = async (message_id) => {
  let sql =
    'select * from comments where message_id = ? order by comment_time desc'
  try {
    const result = await execSql(sql, [message_id])
    return result
  } catch (error) {
    console.log(error)
  }
}

// 新建留言
const createMessage = async (insertData) => {
  let sql = 'insert into messages set ?'
  try {
    const result = await execSql(sql, insertData)
    return result
  } catch (error) {
    console.log(error)
  }
}

// 新建评论
const createComment = async (insertData) => {
  let sql_insert = 'insert into comments set ?'
  let sql_update =
    'update messages set comments_num = comments_num + 1 where message_id = ?'
  try {
    const result = await execSql(sql_insert, insertData) // 在评论表中插入数据
    await execSql(sql_update, [insertData.message_id]) // 在留言表中将对应的留言的评论数+1
    return result
  } catch (error) {
    console.log(error)
  }
}

// 点赞 || 取消点赞
const handleLike = async (data) => {
  try {
    if (data.isLike) {
      // isLike 为 true，表明留言的状态为已被点赞，此时执行取消点赞的逻辑
      // 1. 从点赞表中删除用户点赞留言的记录
      await execSql(
        'delete from likes where username = ? and message_id = ?',
        [data.username, data.message_id]
      )
      // 2. 留言表中该留言对应的点赞数 - 1
      await execSql(
        'update messages set likes_num = likes_num - 1 where message_id = ?',
        [data.message_id]
      )
    } else {
      // isLike 为 false，表明留言的状态为未点赞，此时执行点赞的逻辑
      // 1. 往点赞表中添加用户点赞留言的记录
      await execSql(
        'insert into likes set ?',
        {username: data.username, message_id: data.message_id}
      )
      // 2. 留言表中该留言对应的点赞数 + 1
      await execSql(
        'update messages set likes_num = likes_num + 1 where message_id = ?',
        [data.message_id]
      )
    }
  } catch (error) {
    console.log(error)
  }
}

module.exports = {
  getMessages,
  getComments,
  createMessage,
  createComment,
  handleLike
}
